
#include "Graphic.h"
#include <algorithm>

namespace Graphics
{
	Graphic::Graphic(void)
        :m_Dirty(true)
        ,m_Rendering(false)
	{
	}

	Graphic::~Graphic(void)
	{
	}

    class CallRender
    {
    private:
        bool& m_Result;

    public:
        CallRender(bool& result)
            :m_Result(result)
        {
        }

        inline void operator()(Renderable* obj)
        {
            if(obj->GetVisible())
            {
                m_Result &= obj->Render();
            }
        }
    };

	bool Graphic::RenderAll(void)
	{
        _ASSERT( m_Rendering = true );

        if(m_Dirty)
        {
            m_Dirty = false;
            std::sort(m_Renders.begin(), m_Renders.end(), CompRenderable());
        }

		bool result = true;

        std::for_each(m_Renders.begin(), m_Renders.end(), CallRender(result));

        _ASSERT( m_Rendering = false || true );

		return result;
	}

	Renderable& Graphic::Add(Renderable& obj)
	{
        MarkDirty();

        _ASSERT(!m_Rendering);

        m_Renders.push_back(&obj);
        return obj;
	}

	void Graphic::Remove(Renderable& obj)
	{
        MarkDirty();
        //
	}

    void Graphic::MarkDirty()
    {
        m_Dirty = true;
    }
}